package work.chenbo.mybatis.customize.session.impl;

import work.chenbo.mybatis.customize.config.Configuration;
import work.chenbo.mybatis.customize.config.MappedStatement;
import work.chenbo.mybatis.customize.pojo.BoundSql;
import work.chenbo.mybatis.customize.session.Executor;
import work.chenbo.mybatis.customize.utils.GenericTokenParser;
import work.chenbo.mybatis.customize.utils.ParameterMapping;
import work.chenbo.mybatis.customize.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ChenBo
 * @className DefaultExecutor
 * @date 2020/12/24
 */
public class SimpleExecutor implements Executor {

    private Connection connection;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        DataSource dataSource = configuration.getDataSource();
        connection = dataSource.getConnection();
        BoundSql boundSql = this.getBoundSql(mappedStatement.getSql());

        String sql = boundSql.getSqlTest();
        Class<?> parameterType = mappedStatement.getParameterType();
        PreparedStatement preparedStatement = this.connection.prepareStatement(sql);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = mappedStatement.getResultType();
        ArrayList<E> list = new ArrayList<>();
        while (resultSet.next()){
            E o = (E) resultType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String catalogName = metaData.getColumnName(i);
                Object object = resultSet.getObject(catalogName);
                PropertyDescriptor propertyDescriptor = new
                        PropertyDescriptor(catalogName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,object);
            }
            list.add(o);
        }
        return list;
    }

    private BoundSql getBoundSql(String sqlTest){
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sqlTest);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
